/*登录-cookie */
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); }
    }
    return "";
}
function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("欢迎回来，" + user);
    }
    else {
        user = prompt("请输入你的名字:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 30);
        }
    }
}


/*计划表单操作-indexDB持久化存储 */
(function () {
    var eleForm = document.querySelector('#form'); //填写的表单
    var eleTbody = document.querySelector('#result tbody');//表单展示
    var eleStatus = document.getElementById('status');//表单状态
    var strTplList = document.getElementById('tplList').innerHTML;//表单数据

    var logError = function (error) {
        eleStatus.style.display = 'block';
        eleStatus.innerHTML = '<span class="error">' + error + '</span>';
    }, logInfo = function (info) {
        eleStatus.style.display = 'block';
        eleStatus.innerHTML = '<span class="info">' + info + '</span>';
    };

    String.prototype.temp = function (obj) {
        return this.replace(/\$\w+\$/gi, function (matchs) {
            return obj[matchs.replace(/\$/g, "")] || '';
        });
    };

    var dbName = 'project'; // 数据库名称project
    var version = 1;
    var db;

    var DBOpenRequest = window.indexedDB.open(dbName, version);

    DBOpenRequest.onerror = function (event) {
        logError('数据库打开失败');
    };

    DBOpenRequest.onsuccess = function (event) {
        db = DBOpenRequest.result;
        method.show();
    };

    //数据库首次创建版本
    DBOpenRequest.onupgradeneeded = function (event) {
        var db = event.target.result;

        db.onerror = function (event) {
            logError('数据库打开失败');
        };

        // 创建一个数据库存储对象
        var objectStore = db.createObjectStore(dbName, {
            keyPath: 'id',
            autoIncrement: true
        });

        // 定义存储对象的数据项
        objectStore.createIndex('id', 'id', {
            unique: true
        });
        objectStore.createIndex('name', 'name');
        objectStore.createIndex('begin', 'begin');
        objectStore.createIndex('end', 'end');
        objectStore.createIndex('person', 'person');
        objectStore.createIndex('remark', 'remark');
    };

    var method = {
        //添加数据
        add: function (newItem) {
            var transaction = db.transaction([dbName], "readwrite");// 打开已经存储的数据对象
            var objectStore = transaction.objectStore(dbName); // 添加到数据对象中
            var objectStoreRequest = objectStore.add(newItem);
            objectStoreRequest.onsuccess = function (event) {
                method.show();
            };
        },
        // 编辑数据
        edit: function (id, data) {
            var transaction = db.transaction([dbName], "readwrite");
            var objectStore = transaction.objectStore(dbName);
            var objectStoreRequest = objectStore.get(id);
            objectStoreRequest.onsuccess = function (event) {
                var myRecord = objectStoreRequest.result;
                // 遍历替换
                for (var key in data) {
                    if (typeof myRecord[key] != 'undefined') {
                        myRecord[key] = data[key];
                    }
                }
                objectStore.put(myRecord);// 更新数据库存储数据   
            };
        },
        //删除数据
        del: function (id) {
            var objectStore = db.transaction([dbName], "readwrite").objectStore(dbName);
            var objectStoreRequest = objectStore.delete(id);
            objectStoreRequest.onsuccess = function () {
                method.show();
            };
        },
        //展示数据
        show: function () {
            var htmlProjectList = '';
            var objectStore = db.transaction(dbName).objectStore(dbName);
            objectStore.openCursor().onsuccess = function (event) {// 使用游标
                var cursor = event.target.result;
                if (cursor) {
                    htmlProjectList = htmlProjectList + strTplList.temp(cursor.value);
                    cursor.continue();
                } else {
                    logInfo('');
                    eleTbody.innerHTML = htmlProjectList;
                    if (htmlProjectList == '') {
                        logInfo('暂无数据');
                    }
                }
            }
        }
    };

    // 表单提交新增数据
    eleForm.addEventListener('submit', function (event) {
        event.preventDefault();

        var formData = {};

        [].slice.call(this.querySelectorAll('input,textarea')).forEach(function (ele) {
            if (ele.name) {
                formData[ele.name] = ele.value;
            }
        });

        // 添加新的数据
        method.add(formData);

        this.reset();
    });

    // 编辑事件
    eleTbody.addEventListener('focusout', function (event) {
        var eleTd = event.target;
        // 获取id，也就是获得主键
        var id = eleTd && eleTd.getAttribute('data-id');
        if (!id || !/td/.test(eleTd.tagName)) { return; }

        // 替换的数据
        var data = {
            id: id * 1
        };
        // 获得现在的数据
        [].slice.call(eleTd.parentElement.querySelectorAll('td[data-key]')).forEach(function (td) {
            var key = td.getAttribute('data-key');
            var value = td.innerText || td.textContent || '';

            data[key] = value;
        });

        // 更新
        method.edit(id, data);
    });
    // 删除事件
    eleTbody.addEventListener('click', function (event) {
        var eleBtn = event.target, id = '';
        if (eleBtn && eleBtn.classList.contains('jsListDel') && (id = eleBtn.getAttribute('data-id'))) {
            method.del(id * 1);
            event.preventDefault();
        }
    });
})();


/*标题焦点变化 */
window.onblur = function () {
    document.title = "_(:з)∠)_计划持续摸鱼中";
};
window.onfocus = function () {
    document.title = "(oﾟvﾟ)ノ计划绝赞进行中";
};